package com.example.search;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.ExistsRequest;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class ProductIndexInitializer {
    private static final Logger log = LoggerFactory.getLogger(ProductIndexInitializer.class);
    public static final String INDEX = "products";

    private final ElasticsearchClient client;

    public ProductIndexInitializer(ElasticsearchClient client) {
        this.client = client;
    }

    @PostConstruct
    public void ensureIndex() {
        try {
            boolean exists = client.indices().exists(ExistsRequest.of(b -> b.index(INDEX))).value();
            if (exists) {
                log.info("Index {} already exists", INDEX);
                return;
            }

            // 使用 withJson 方式创建索引（版本无关）
            CreateIndexResponse create = client.indices().create(c -> c
                    .index(INDEX)
                    .withJson(new java.io.StringReader("""
                {
                  "settings": {
                    "number_of_shards": 1,
                    "number_of_replicas": 0,
                    "analysis": {
                      "filter": {
                        "edge_ngram_filter": {"type": "edge_ngram", "min_gram": 1, "max_gram": 15}
                      },
                      "analyzer": {
                        "edge_ngram_analyzer": {
                          "tokenizer": "standard",
                          "filter": ["lowercase", "edge_ngram_filter"]
                        }
                      }
                    }
                  },
                  "mappings": {
                    "properties": {
                      "name": {
                        "type": "text",
                        "analyzer": "standard",
                        "search_analyzer": "standard",
 
                        "fields": {
                          "partial": {"type": "text", "analyzer": "edge_ngram_analyzer"}
                        }
                      },
                      "category": {"type": "keyword", "ignore_above": 256},
                      "price": {"type": "double"},
                      "rating": {"type": "double"},
                      "color": {"type": "keyword", "ignore_above": 128},
                      "size": {"type": "keyword", "ignore_above": 64},
                      "attributes": {
                        "properties": {
                          "brand": {"type": "keyword"},
                          "material": {"type": "keyword"},
                          "color": {"type": "keyword"},
                          "size": {"type": "keyword"}
                        }
                      }
                    }
                  }
                }
                """))
            );

            log.info("Created index {} acknowledged={} shardsAck={}", INDEX, create.acknowledged(), create.shardsAcknowledged());
        } catch (Exception e) {
            log.warn("Elastic not available at startup, skip index init: {}", e.getMessage());
        }
    }
}